package com.guoliang.wechatpushing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.guoliang.wechatpushing.constant.Constant;
import com.guoliang.wechatpushing.service.HandlerService;
import com.guoliang.wechatpushing.service.SendMessageService;
import com.guoliang.wechatpushing.utils.RestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Leo
 * @date ：Created in 2022/10/18 18:46
 * @description：
 */
@Service
@Slf4j
public class SendMessageServiceImpl implements SendMessageService {
    @Autowired
    Constant constant;
    @Autowired
    HandlerService handlerService;
    @Override
    public boolean sendMessage() {
        boolean isSend=true;  //判断用户是否全部推送成功
        List<String> receiverIds = constant.receiver;
        Map<String, Object> resultMap = handlerService.handlerMessage();
        String token = getToken();
        for (String receiverId : constant.receiver) {
           if (!send(resultMap,receiverId,token)) isSend=false;
        }
        if (isSend){
            log.info("已经全部推送成功");
            constant.count++;
        }
        return isSend;
    }

    @Override
    public String getToken() {
        String url="https://api.weixin.qq.com/cgi-bin/token";
        Map<String,Object> map=new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",constant.appID);
        map.put("secret",constant.appsecret);
        JSONObject jsonObject = RestUtil.sendGetRequest(RestUtil.getRestTemplate(), url, map,JSONObject.class);
        String access_token = (String)jsonObject.get("access_token");
//        System.out.println(access_token);
        return access_token;
    }

    @Override
    public boolean send(Map<String,Object> resultMap,String touser,String token) {
        String url="https://api.weixin.qq.com/cgi-bin/message/template/send";
        Map<String,Object> map=new HashMap<>();
        map.put("touser",touser);
        map.put("template_id",constant.template_id);
        map.put("data",resultMap);
        String s = JSONObject.toJSONString(map);
        Map<String,Object> param=new HashMap<>();
        param.put("access_token",token);
        JSONObject jsonObject = RestUtil.sendPostRequest(RestUtil.getRestTemplate(), url, s, param, JSONObject.class);
        Integer code=(Integer)jsonObject.get("errcode");
        if (0==code) {
            log.info("用户"+touser+"推送成功");
            return true;
        }
        else return false;
    }
}
